from tracemalloc import take_snapshot

import jieba
txt = open("西游记.txt","rb").read()
exinclude = {"一个", "那里", "怎么", "我们", "不知", "两个", "甚么",
              "只见", "不是","原来", "不敢", "闻言", "如何", "什么"}
word = jieba.lcut(txt)  #将分词结果直接转化为列表

def takesecond(el): #返回一个元素的第二个数据
    # print(el)
    return el[1]
'''
孙悟空   次数
猪八戒   次数
沙僧   次数
唐僧   次数
'''
# word = ["孙悟空","猪八戒","猪八戒","孙悟空","孙悟空","孙悟空","沙僧","沙僧","唐僧","唐僧"]
words = {} #创建字典用于存储统计结果

for w in word:

    if len(w) == 1 or w == '\r\n':
        continue  # 如果发现不符合长度要求的文字，直接退出循环
    if w=="行者" or w =="大圣" or w == "老孙" or w == "孙爷爷" or w == "悟空" or w == "孙行者" or w=="孙大圣":
        gWord = "孙悟空"
    elif w=="师父" or w =="三藏" or w == "长老" or w == "唐僧":
        gWord = "唐僧"
    elif w == "八戒" or w == "老猪" or w == "二师兄" or w == "悟能":
        gWord = "八戒"
    elif w == "沙僧" or w == "沙和尚" or w == "悟净":
        gWord = "沙僧"
    else :
        gWord = w;
    words[gWord] = words.get(gWord,0) + 1;

for ex in exinclude:
    del words[ex]  #将需要排除的词删除

items = list(words.items())   #words.items()将字典转换成元组，list(words.items())将元组转换成列表，为了方便排序。

items.sort(key=takesecond,reverse=True)  #利用函数对第二个数进行排序
# print(items)

for i in range(9):
    word,count = items[i]
    print("%s\t\t%d次"%(word,count))




#
# print(words.keys())

